package practise.hibernate.Service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import practise.hibernate.Service.PersonService;
import practise.hibernate.dao.AddressDao;
import practise.hibernate.dao.PersonDao;
import practise.hibernate.persistence.Person;

import java.util.List;

@Service("personService")
@Repository
@Transactional
public class PersonServiceImpl implements PersonService {

    @Autowired
    private AddressDao addressDao;

    @Autowired
    private PersonDao personDao;

    @Override
    @Transactional(readOnly = true, propagation = Propagation.REQUIRED)
    public List<Person> findAllPersons() {
        return personDao.findAllPersons();
    }

    @Override
    @Transactional(readOnly = false , propagation = Propagation.REQUIRED)
    public Person addPerson(Person person) {
        return personDao.merge(person);
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public Person updatePersonAge(String name, int age){
        List<Person> persons = personDao.findPersonByName(name);
        Person personUpdating = null ;
        for(Person person : persons){
            if(person.getFirstName().equals(name)){
                personUpdating= person;
                break;
            }
        }

        personUpdating.setAge(age);
        return  personUpdating;
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public void deleteAddress(int id) {
        personDao.deleteAddress(id);
    }

    @Override
    @Transactional(readOnly = true, propagation = Propagation.REQUIRED)
    public List<Person> findPersonByName(String name) {
        return personDao.findPersonByName(name);
    }
}
